<template>
  <div>
    <van-nav-bar title="人物详情页"  left-arrow @click-left="$router.back()"  />

    <div class="img">
      <!-- 修正 src 绑定，调用 getId() 方法 -->
      <img :src="imageUrl" alt="人物图片"  />
    </div>
    <!-- SKU 组件，绑定show来控制是否显示 -->
    <van-goods-action>
      <van-goods-action-icon @click="$router.push('/')" icon="wap-home-o" text="首页"  />
      <van-goods-action-icon @click="$router.push('/cart')" icon="cart-o" text="购物车" :badge="addNum" />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="" />
      <van-goods-action-button type="warning" text="加入购物车" @click="showPopupAdd"/>
      <van-goods-action-button type="danger" text="立即购买" @click="showPopupBuy" />
    </van-goods-action>
    <van-popup v-model="show"
      position="bottom"
      :style="{ height: '40%' }"
      v-if="show"
      closeable
      round
      duration="1"
    >
      <h3>{{ popupText }}</h3>
      <van-card
        :price="price"
        :desc="description"
        :title="name"
        :thumb="imageUrl"
      />
      <div class="num">
        <div class="left"><strong>{{ quantity }}</strong></div>
        <div class="right"><num v-model="count" :mode="'reduce'" ></num></div>
      </div>
      <van-button type="primary" size="large" @click="addCart">{{ popupText }}</van-button>
    </van-popup>
  </div>
</template>

<script>
import num from '@/components/num.vue'
import store from '@/store'
import { mapState } from 'vuex'
import { Dialog } from 'vant'
import request from '@/utils/request'
export default {
  name: 'proDetailIndex',
  data () {
    return {
      show: false,
      popupText: '加入购物车',
      count: 1, // 要买多少
      quantity: '', // 库存数量
      imageUrl: '',
      imageUrl1: '', // 没有拼接过的图片路径地址
      name: '',
      description: '',
      price: '',
      productId: '',
      addNum: ''
    }
  },
  components: {
    num
  },
  created () {
    this.getImageUrl()
    this.showCartNum()
  },
  computed: {
    ...mapState('cart', ['cart'])
  },
  methods: {
    // 获取 id 参数
    async getImageUrl () {
      const id = this.$route.query.id
      const res = await request.get(`/getTransform?tags=${id}`)
      this.productId = id
      this.imageUrl = require(`@/assets/${res.data[0].image_url}`)
      this.imageUrl1 = res.data[0].image_url
      this.name = res.data[0].name
      this.description = res.data[0].description
      this.price = res.data[0].price
      this.quantity = res.data[0].quantity
    },
    showPopupAdd () {
      this.popupText = '加入购物车'
      this.show = !this.show
    },
    showPopupBuy () {
      this.popupText = '立即购买'
      this.show = !this.show
    },
    showCartNum () {
      this.addNum = this.cart.cartNum
    },
    async addCart () {
      // 检验token
      if (!store.state.user.userInfo.token) {
        Dialog.confirm({
          title: '温馨提示',
          message: '需要先进行登录操作哦！',
          confirmButtonText: '去登录',
          cancelButtonText: '再逛逛'
        })
          .then(() => {
            this.$router.replace({
              path: '/login',
              query: {
                redirect: this.$route.fullPath
              }
            })
            // on confirm
          })
          .catch(() => {
            // on cancel
            this.show = !this.show
          })
        return
      }
      const token = store.state.user.userInfo.token
      // 判断popupText来判断是加入购物车还是立即购买
      if (this.popupText === '立即购买') {
        const res = await request.post('/buyNow', {
          userId: store.state.user.userInfo.userId,
          productId: this.productId,
          quantity: this.count,
          price: this.price,
          imageUrl: this.imageUrl1,
          description: this.description
        }, {
          headers: {
            Authorization: token
          }
        })
        if (res.status === 200) {
          this.$toast(res.message)
        } else {
          this.$toast(res.message)
        }
      }

      const res = await request.post('/addCart', {
        userId: store.state.user.userInfo.userId,
        productId: this.productId,
        quantity: this.count,
        price: this.price,
        imageUrl: this.imageUrl1,
        description: this.description
      }, {
        headers: {
          Authorization: token
        }
      })
      this.addNum = res.addNum
      if (res.status === 200) {
        this.$toast(res.message)
      } else {
        this.$toast(res.message)
      }
      // const { userId, productId, quantity, price } = req.body;
      this.show = !this.show
    }
  }
}
</script>

<style>
.my-swipe .van-swipe-item {
  color: #fff;
}
.my-swipe img {
  width: 100%;
  height: 150px;
}
.img img {
  width: 100%;
  height: 250px;
}
.van-popup {
  text-align: center;
}
.num {
  display: flex;
  justify-content: space-between;
}
.num .left {
  margin-left: 10px;
  margin-top: 10px;
}
</style>
